from rest_framework import serializers

from apps.goods.models import SKUImage, SKU


class SKUImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKUImage
        fields = '__all__'

"""
    def create(self, validated_data):
        # 创建模型类对象 保存到数据库
        # 1前端传过来的参数 都在validated_data字典里
        image = validated_data.get('image')
        sku = validated_data.get('sku')
        sku_id = sku.id

        image_data = image.read()  # 获取图片 的二进制数据
        # 2校验参数
        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            print(e)
            #raise serializers.ValidationError("验证失败")

        # 3保存数据
        # 上传的fdfs
        from fdfs_client.client import Fdfs_client
        client = Fdfs_client('utils/fastdfs/client.conf')
        result = client.upload_by_buffer(image_data)
        # {'Remote file_id': 'group1/M00/00/00/wKjlhFsTgJ2AJvG_AAAyZgOTZN0850.jpg', 'Uploaded size': '12.00KB',
        #  'Local file name': '/home/python/Desktop/images/0.jpg', 'Storage IP': '192.168.229.132',
        #  'Group name': 'group1', 'Status': 'Upload successed.'}
        if result.get("Status") != 'Upload successed.':
            # return Response(status=status.HTTP_400_BAD_REQUEST)
            raise serializers.ValidationError("上传失败")

        print("上传图片成功")
        file_id = result.get("Remote file_id")
        print("file_id", file_id)
        # 保存到数据库
        sku_image = SKUImage.objects.create(sku_id=sku_id, image=file_id)
        print("sku_image", sku_image)

        # 4返回响应
        return sku_image
"""
# 序列化  把模型类数据 转  字典
# 反序列化 字典 转 模型类数据

class SKUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ['id', 'name']
